<?php
namespace app\index\controller;
use app\index\controller\Home;
use think\Session;
use think\Request;

class Collect extends Home
{
    /**
     * 收藏帖子
     */
    public function collect ()
    {
        //如果没有登录,就不能收藏,返回数字0
        if(empty(session("home"))){
            echo 0;
            die;
        }

        //获取帖子id
        $card_id = Request::instance()->param("card_id");
        //获取用户id
        $user_id = session("home.id");

        //在收藏表中查询 ,该用户是否已经收藏该贴
        $data['user_id'] = $user_id;
        $data['card_id'] = $card_id;

        $collect = model("collect");
        // 根据条件(数组)查询收藏表,如果有数据返回1 反之返回0
        $result = $collect -> queryCollect($data);

        $card = model("card");
        if($result == 0){
            //向收藏表中添加数据
            $res = $collect -> addCollect($data);
            if($res > 0){
                //收藏成功,帖子的收藏数自加1
                $card->setIncCard("id=$card_id","collect_num",1);
                echo 1;
            }else{
                echo 3;
            }
        }else{
            //删除数据
            $res = $collect -> deleteCollect($data);
            if($res > 0){
                //删除成功,帖子的收藏数自减1
                $card->setDecCard("id=$card_id","collect_num",1);
                echo 2;
            }else{
                echo 3;
            }
        }

    }

    /**
     * 查看该用户是否收藏该贴
     */
    public function showCollect ()
    {
        //如果没有登录,就不能收藏,返回数字0
        if(empty(session("home"))){
            echo 2;
            die;
        }

        //获取帖子id
        $card_id = Request::instance()->param("card_id");
        //获取用户id
        $user_id = session("home.id");

        //在收藏表中查询 ,该用户是否已经收藏该贴
        $data['user_id'] = $user_id;
        $data['card_id'] = $card_id;

        $collect = model("collect");
        // 根据条件(数组)查询收藏表,如果有数据返回1 反之返回0
        $result = $collect -> queryCollect($data);
        echo $result;
    }
}
?>